package com.serve.oa.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.serve.oa.common.lang.Const;
import com.serve.oa.common.lang.Result;
import com.serve.oa.converter.BaseDateConverter;
import com.serve.oa.dto.UserAddDto;
import com.serve.oa.dto.UserUpdateDto;
import com.serve.oa.entity.SysRole;
import com.serve.oa.entity.SysUser;
import com.serve.oa.entity.SysUserRole;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.runtime.Debug;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author __tyw
 * @since 2022-10-18
 */
@Api(tags = "用户模块")
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {


    @ApiOperation(value = "当前用户信息")
    @GetMapping("/current")
    public Result current(){
        return Result.succ(curUser()) ;
    }

    @ApiOperation(value = "查询用户列表")
    @GetMapping("/list")
    @RequiresPermissions("sys:user:list")

    public Result list(String username){

        Page<SysUser> pageData = userService.page(getPage(),new QueryWrapper<SysUser>()
                .like(StrUtil.isNotBlank(username), "username", username));
        pageData.getRecords().forEach(u->{
            u.setSysRoles(roleService.listRolesByUserIdSe(u.getId()));

        });
        return Result.succ(pageData) ;
    }


    @ApiOperation(value = "查询其他系统用户列表")
    @GetMapping("/listAll")
    @RequiresPermissions("sys:user:list")
    //@Cacheable(value = "listAll" ,key = "'sada'")
    public Result list2(){

        List<SysUser> pageData = userService.list();
       // List<Map> pageData1 = userService.listAll();
        String s  = userService.getTime("33");
        List<SysUser> pageData3 = userService.chaList();
        Map map = new HashMap();
        map.put("l",pageData);
      //  map.put("m",pageData1);
        map.put("t",s);
        map.put("s",pageData3);


        return Result.succ(map) ;
    }

    @GetMapping("/export")
    @RequiresPermissions("sys:user:export")
    public void export(HttpServletResponse response) throws IOException {



      try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            String fileName = URLEncoder.encode("导出", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            List<SysUser> studentList = userService.list();
            // 这里需要设置不关闭流
            // 设置excel表格样式



            EasyExcel.write(response.getOutputStream(), SysUser.class)
                    .registerConverter(new BaseDateConverter.LocalDateConverter())
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("导出详情")
                    .doWrite(studentList);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }


    }
    @ApiOperation(value = "查单个用户")
    @GetMapping("/info/{id}")
    @Transactional
    @RequiresPermissions("sys:user:list")
    public Result info(@PathVariable("id") Long id) {

        SysUser sysUser = userService.getById(id);
        Assert.notNull(sysUser, "找不到用户");

        List<Long> roles = roleService.listRolesByUserIdArr(id);

        sysUser.setRoles(roles);
        return Result.succ(sysUser);
    }

    @ApiOperation(value = "更新用户")
    @PostMapping("/update")
    @Transactional
    @RequiresPermissions("sys:user:update")
    public Result update(@Validated @RequestBody UserUpdateDto userAddDto){

        if(userAddDto.getId() == null){
            return Result.fail("id必传");
        }else {


            Assert.notNull(userService.getById(userAddDto.getId()), "id无效");

            SysUser user = new SysUser();
            user.setId(userAddDto.getId());
            user.setCreated(LocalDateTime.now());

            user.setCreated(LocalDateTime.now());
            user.setStatu(Const.STATUS_OFF);
            user.setCity(userAddDto.getCity());
            user.setEmail(userAddDto.getEmail());

            // 默认密码
            user.setUsername(userAddDto.getUsername());

            // 默认头像
            user.setAvatar(userAddDto.getAvatar());
            userService.updateById(user);


            userRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id",userAddDto.getId()));
            List<SysUserRole> list = new ArrayList<>();
            userAddDto.getRoles().forEach(r -> {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(userAddDto.getId());
                sysUserRole.setRoleId(r);
                list.add(sysUserRole);
            });

            userRoleService.saveBatch(list);

            //清楚缓存用户
            redisTemplate.delete("perm:"+user.getUsername());


            return Result.fail(200,"成功",user);
        }

    }

    @ApiOperation(value = "新增用户")
    @PostMapping("/add")
    @Transactional
    @RequiresPermissions("sys:user:add")
    public Result add(@Validated @RequestBody UserAddDto userAddDto){

        SysUser ds =  userService.getOne(new QueryWrapper<SysUser>().eq("username",userAddDto.getUsername()));

        if(ds==null){
            //System.out.println(userAddDto.getRoles().toString());
            SysUser user = new SysUser();
            user.setCreated(LocalDateTime.now());

            user.setCreated(LocalDateTime.now());
            user.setStatu(Const.STATUS_OFF);
            user.setCity(userAddDto.getCity());
            user.setEmail(userAddDto.getEmail());

            // 默认密码
            String password = SecureUtil.md5(userAddDto.getPassword());
            user.setPassword(password);
            user.setUsername(userAddDto.getUsername());

            // 默认头像
            user.setAvatar(Const.DEFULT_AVATAR);
            userService.save(user);
            List<SysUserRole> list = new ArrayList<>();
            userAddDto.getRoles().forEach(r -> {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(user.getId());
                sysUserRole.setRoleId(r);
                list.add(sysUserRole);
            });


            userRoleService.saveBatch(list);
            return Result.succ(user) ;
        }else {
            return Result.fail("用户存在了");
        }

    }


    @PostMapping("/delete")
    @ResponseBody
    @Transactional
    @RequiresPermissions("sys:user:delete")
    public Result delete(@RequestBody Map<String, Integer> params) {

        //System.out.println(params.get("id"));
        userService.removeById(params.get("id"));
        userRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", params.get("id")));

        return Result.succ(200,"删除了",null);
    }



}


